import express from "express";
import { createSSRApp } from "vue";
import { renderToString } from "vue/server-renderer";

import { createApp, createAbout } from "./app.js";

// 创建 express 实例
const server = express();

// 静态资源托管
server.use(express.static("."));

// 路由
server.get("/", (req, res) => {
  // 创建 ssr 的应用实例
  const app = createApp();

  // 转换成静态的 html 并渲染出去
  renderToString(app).then((html) => {
    res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Vue SSR Example</title>
      </head>
      <body>
        <div id="app">${html}</div>

        <script type="importmap">
          {
            "imports": {
              "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
            }
          }
        </script>
        <script type="module" src="/client.js"></script>
      </body>
    </html>
    `);
  });
});

server.get("/about", (req, res) => {
  // 1. 获取 Vue 的应用实例
  const app = createAbout();

  // 2. 将 应用实例转换成 html
  renderToString(app).then((html) => {
    // 3. 输出到浏览器

    res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Vue SSR Example</title>
      </head>
      <body>
        <div id="app">${html}</div>

        <script type="importmap">
          {
            "imports": {
              "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
            }
          }
        </script>
        <script type="module" src="/client-about.js"></script>
      </body>
    </html>

    `);
  });
});

// 监听端口
server.listen(3000, () => {
  console.log("ready");
});
